Ext.require([
    'Ext.form.*',
    'Ext.layout.container.Column',
    'Ext.tab.Panel',
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.toolbar.Paging',
    'Ext.ModelManager',
    'Ext.selection.*',
    'Ext.Toolbar'
]);

Ext.onReady(function() {	
	var date = new Date();
	var nowYear = date.getFullYear(); 
	var yearData = [];
	for(var i = nowYear - 3; i <= nowYear; i++) {
		yearData.push({value: i,text: i});
	}
	
	function getMonth(quarter) {
		var monthData = [];
		monthData.push({value: 0, text:'全部'});
		
		if(quarter > 0) {
			var startM = 3 * (quarter - 1);
			for(var i = startM ; i < startM + 3; i++) {
				monthData.push({
					value: i + 1,
					text: Ext.Date.monthNames[i % 12]
				});
			}
		}
		return monthData;
	}
	
	var monthStore = Ext.create('Ext.data.JsonStore', {
		fields: ['value', 'text'],
		data: getMonth(0)
	});
	
	var searchForm = Ext.create('Ext.form.Panel', {
//		frame: true,
//		title: '查询',
//		collapsible : true,
//		collapsed: false,
//		collapseMode:'mini',
		region: 'north',
		height: 45,
		split: false,
		fieldDefaults: {
            labelAlign: 'right',
            labelWidth: 80,
            msgTarget: 'side'
        },
		items: [
			{
				frame: true,
				layout: {
                    type: 'hbox',
                    padding:'5',
                    pack:'start',
                    align:'middle'
                },
                defaults:{margins:'0 5 0 0'},
                items:[
                	Ext.create('Ext.form.ComboBox', {
                		fieldLabel: '年度',
						name: 'year',
						hiddenName: 'year',
						triggerAction: 'all', 
						allowBlank: false,
						editable: false,
						anchor : '95%',
						queryMode: 'local',
						valueField: 'value',
						value: 2011,
						displayField: 'text',
						store: Ext.create('Ext.data.JsonStore', {
							fields: ['value', 'text'],
							data: yearData
						})
					}),
                	Ext.create('Ext.form.ComboBox', {
						fieldLabel: '季度',
						name: 'quarter',
						hiddenName: 'quarter',
						triggerAction: 'all', 
						editable: false,
						anchor : '95%',
						value: 1,
						queryMode: 'local',
						valueField: 'value',
						displayField: 'text',
						store: new Ext.data.SimpleStore({
							fields: ['value', 'text'],
							data: [[1, 'Q1'],[2, 'Q2'],[3, 'Q3'],[4, 'Q4']]
						}),
						listeners : {
				            select : function(ComboBox, record, index) {
				            	monthStore.loadData(getMonth(ComboBox.value));
				            }
				        }
					}),
					Ext.create('Ext.form.ComboBox', {
						fieldLabel: '月份',
						id: 'monthCombo',
						name: 'month',
						hiddenName: 'month',
						triggerAction: 'all', 
						editable: false,
						anchor : '95%',
						value: 1,
						queryMode: 'local',
						valueField: 'value',
						displayField: 'text',
						store: monthStore
					}),
                	{
				   		xtype: 'button',
				   		text: '签单统计',
						anchor : '97%',
						handler: function() {
							var fv = searchForm.getForm().getValues();
							store.proxy.extraParams= fv;
							store.loadPage(1);
						}
				   },
                	{
				   		xtype: 'button',
				   		text: '收入统计',
						anchor : '97%',
						handler: function() {
						}
				   }
                ]
			}
		]
	});
	
	Ext.define('ForumThread', {
        extend: 'Ext.data.Model',
        fields: [
           	{name: 'customerGroup'},
			{name: 'f_amount_week'},
			{name: 'f_amount'},
			{name: 'f_income'},
			{name: 'f_estimate'},
			{name: 'f_finishRatio'},
			{name: 'f_arup'},
			{name: 'amount',  type: 'float'},
			{name: 'income',  type: 'float'},
			{name: 'amount_week',  type: 'float'},
			{name: 'estimate',  type: 'float'},
			{name: 'arup',  type: 'float'}
        ],
        idProperty: 'customerGroup'
    });
    
	var store = Ext.create('Ext.data.Store', {
    	pageSize: 10000,
        model: 'ForumThread',
        remoteSort: false,
        proxy: {
        	type: 'ajax',
            url: 'http://localhost:8088/AdStatE/HTML/customer/CustomerGroupAction/search.action',
            reader: {
            	type : 'json',
                root: 'invdata',
                totalProperty: 'total',
                otherInfo: 'otherInfo'
            },
            extraParams: {year:2011, quarter: 1, month: 1},
            simpleSortMode: true
        },
        sorters: [{
            property: 'amount',
            direction: 'desc'
        }]
    });
    
    var detailWin;
    
    window.showGroupDetail = function(groupname) {
    	
    	if(!detailWin) {
    		detailWin = Ext.create('Ext.Window', {
    			title: '详细信息',
				modal: true,
				layout:'fit',
				width:850,
				height:500,
				closeAction:'hide',
				plain: true,
				html: '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="http://www.baidu.com/"></iframe>'
    		});
    	}
    	
    	detailWin.update({
    		title: groupname,
			html: '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="customergroup_detail.jsp?customergroupName='+ encodeURI(encodeURI(groupname)) +'"></iframe>'
		});
		
		detailWin.show();
    }
    
    function renderGroup(value, cellmeta, record, rowIndex, columnIndex, stor) {
    	return '<a href="#" onclick=\"showGroupDetail(\''+value+'\')">' + value + '</a>';
    }
    
    function rmbMoneyRender(v, cellmeta, record, rowIndex, columnIndex, stor){
        v = (Math.round((v-0)*100))/100;
        v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
        v = String(v);
        var ps = v.split('.');
        var whole = ps[0];
        var sub = ps[1] ? '.'+ ps[1] : '.00';
        var r = /(\d+)(\d{3})/;
        while (r.test(whole)) {
            whole = whole.replace(r, '$1' + ',' + '$2');
        }
        v = whole + sub;
        if(v.charAt(0) == '-'){
            return '-￥' + v.substr(1);
        }
        return "￥" +  v;
    };
    
    var grid = Ext.create('Ext.grid.Panel', {
		region: 'center',
        store: store,
//        disableSelection: true,
        loadMask: true,
//        selModel: sm,
        columns:[
        	Ext.create('Ext.grid.RowNumberer', {width:40}),
        	{header:'直客集团', dataIndex:'customerGroup', flex: 10, renderer: renderGroup, sortable:true},
			{header:'本周签单金额', dataIndex:'amount_week',  flex: 10, sortable:true, align: 'right',renderer:rmbMoneyRender},
			{header:'当期签单金额', dataIndex:'amount', flex: 10, sortable:true, align: 'right', renderer:rmbMoneyRender},
			{header:'当期收入金额', dataIndex:'income',  flex: 10, sortable:true, align: 'right',renderer:rmbMoneyRender},
			{header:'当期预估签单', dataIndex:'estimate',  flex: 10, sortable:true, align: 'right',renderer:rmbMoneyRender},
			{header:'完成比', dataIndex:'f_finishRatio',  flex: 10, sortable:true,  align: 'center',
				renderer: function(v) {
					return v + "%";
				}
			},
			{header:'ARPU', dataIndex:'arup',  flex: 10, sortable:true, align: 'right',renderer:rmbMoneyRender}
        ],
		bbar: Ext.create('Ext.PagingToolbar', {
			store: store,
            displayInfo: true,
            displayMsg: '显示第{0}条到{1}条记录,一共{2}条',
			emptyMsg: '没有记录',
			items: [
				'-',
				{
			 		text: '导出Excel',
					iconCls: 'add',
					handler: function() {
						var cms = grid.getColumnModel();
						var strColoumnNames = "";
						var strColoumnIndexs = "";
						for(var i = 0; i < cms.getColumnCount(); i++) {
							if(cms.getColumnHeader(i) == '' || cms.getColumnHeader(i) == '操作')
								continue;
								
							if (!cms.isHidden(i)) {
								strColoumnIndexs += cms.getDataIndex(i) + ',';
								strColoumnNames += cms.getColumnHeader(i) + ',';
							}
						}
						
						window.location.href = '../customer/CustomerGroupAction/doExport.action?exp_name=data.xls&exp_column_names=' + encodeURI(encodeURI(strColoumnNames)) 
							+ '&exp_column_indexs=' + strColoumnIndexs 
							+ '&' + encodeURI(searchForm.getForm().getValues(true)); 
					}
			 	}
			]
		})
    });
	
	store.on("load", function(s,records) {
		if(s.proxy.reader.jsonData.otherInfo != 'isWeek') {
			grid.columns[2].hide();
		}
		else {
			grid.columns[2].show();
		}
	});
    
	store.load();
					
	new Ext.Viewport({
		layout: 'border',
		items:[
			searchForm,grid
		]
	});
});